package com.neusoft.taotao.util;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.neusoft.taotao.bean.Result;

/**
 * 
 * @author chens
 *
 */
public final class StringUtil {
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void error(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Result result = new Result();
		result.setSuccess(Boolean.FALSE);
		result.setErrorMsg("404-地址错误！");
		String json = new Gson().toJson(request);
		write(response, json);
	}

	/**
	 * 判断字符串是否为空 或 为空格字符串
	 * 
	 * @param numString
	 * @return 为空或空字符串返回 - false ,不为空返回 - true
	 */
	public static boolean isNotBlank(String numString) {
		boolean ret = false;
		if (numString != null && numString.trim().length() > 0) {
			ret = true;
		}
		return ret;
	}

	/**
	 * 
	 * @param bool
	 * @return Result
	 */
	public static Result myResult(boolean bool) {
		Result result = new Result();
		if (bool) {
			result.setSuccess(Boolean.TRUE);
			result.setErrorMsg("操作成功！");
		} else {
			result.setSuccess(Boolean.FALSE);
			result.setErrorMsg("操作失败！");
		}
		return result;
	}

	/**
	 * 把字符串转换为double类型
	 * 
	 * @param numString
	 * @return 转换失败返回 - 0.0,转换成功返回对应的double类型值
	 */
	public static double parseDouble(String numString) {
		try {
			return Double.parseDouble(numString);
		} catch (Exception e) {
			return 0.0;
		}
	}

	/**
	 * 把字符串转换为float类型
	 * 
	 * @param numString
	 * @return 转换失败返回 - 0.0,转换成功返回对应的float类型值
	 */
	public static float parseFloat(String numString) {
		try {
			return Float.parseFloat(numString);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 把字符串转换为int类型
	 * 
	 * @param numString
	 * @return 转换失败返回 - 0,转换成功返回对应的int类型值
	 */
	public static int parseInt(String numString) {
		try {
			return Integer.parseInt(numString);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 
	 * @param numString
	 * @param defaultValue
	 * @return 转换失败返回 - defaultValue,转换成功返回对应的int类型值
	 */
	public static int parseInt(String numString, int defaultValue) {
		try {
			return Integer.parseInt(numString);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * 数据类型转json
	 * 
	 * @param response
	 * @param json
	 * @throws ServletException
	 * @throws IOException
	 */
	public static void write(HttpServletResponse response, String json) throws ServletException, IOException {
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().write(json);
		response.getWriter().flush();
		response.flushBuffer();
	}

	private StringUtil() {
	}

}
